package com.pms.timedTask;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pms.controller.BaseController;
import com.pms.exception.R;
import com.pms.partitionPoints.entity.KyEquipmentInfo;
import com.pms.partitionPoints.entity.KyOrganization;
import com.pms.partitionPoints.entity.KyOrganizationParameters;
import com.pms.partitionPoints.service.IKyEquipmentInfoService;
import com.pms.partitionPoints.service.IKyOrganizationParametersService;
import com.pms.partitionPoints.service.IKyOrganizationService;
import com.pms.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 定时任务
 */
@Component
@Configurable
@EnableScheduling
public class Timer extends BaseController {
    @Autowired
    private IKyEquipmentInfoService kyEquipmentInfoService;
    @Autowired
    private IKyOrganizationService kyOrganizationService;
    @Autowired
    private IKyOrganizationParametersService kyOrganizationParametersService;

    /**
     *
     * 测点，修改状态（每5分钟更一次）
     * @return
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public R updateEquipmentStatus(){
        List<KyEquipmentInfo> list = kyEquipmentInfoService.selectList(new EntityWrapper<KyEquipmentInfo>().eq("status",1));
        List<KyEquipmentInfo> updateList = new ArrayList<KyEquipmentInfo>();
        Date d = new Date();
        for(KyEquipmentInfo ki:list){
            Integer orgMaxId = ki.getOrganizationgroupid();
            if(1==ki.getCommunicationstatus()){//状态为1，设备在线的
                Date date = kyOrganizationService.getUploadDateByEquipmentId(orgMaxId,ki.getId());
                if(date==null){
                    ki.setCommunicationstatus(2);
                    ki.setEquipmentstatus(2);
                    updateList.add(ki);
                    continue;
                }
                date = DateUtil.addDate(date,12,5);
                int i = date.compareTo(d);
                if(i==-1){
                    ki.setCommunicationstatus(2);
                    ki.setEquipmentstatus(2);
                    updateList.add(ki);
                }
            }else{//设备不在线的
                Date date = kyOrganizationService.getUploadDateByEquipmentId(orgMaxId,ki.getId());
                if(date==null){
                    continue;
                }
                date = DateUtil.addDate(date,12,5);
                int i = date.compareTo(d);
                if(i==1){
                    ki.setCommunicationstatus(1);
                    ki.setEquipmentstatus(1);
                    updateList.add(ki);
                }
            }
        }
        if(updateList.size()>0){
            kyEquipmentInfoService.updateBatchById(updateList);
        }
        return R.ok();
    }

    /**
     * 对应的分区参数设置延用（每月1号9点15分执行）
     * @return
     */
    @Scheduled(cron = "0 15 9 1 * ?")
    public R addOrganizationParameters() throws Exception {
        List<KyOrganization> list = kyOrganizationService.selectList(new EntityWrapper<>());
        Date date = new Date();
        int year = date.getYear()+1900;
        int month = date.getMonth()+1;
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM");
        List<KyOrganizationParameters> kopList = new ArrayList<>();
        for(KyOrganization ko:list){
            Integer koId = ko.getId();
            KyOrganizationParameters kop = kyOrganizationParametersService.selectOne(new EntityWrapper<KyOrganizationParameters>().eq("organization_id",koId).orderBy("year",false).orderBy("month",false));
            if(kop!=null){
                int yearOnce = kop.getYear();
                int monthOnce = kop.getMonth();
                int n = (year - yearOnce) * 12;
                n = n + month - monthOnce;//所差月份
                List<String> strList = new ArrayList<>();
                if(n<8&&n>2){//半年时间内
                    String endTime = String.valueOf(year).concat("-").concat(String.valueOf(month));
                    String startTime = String.valueOf(yearOnce).concat("-").concat(String.valueOf(monthOnce));
                    strList = DateUtil.getMonthBetween(startTime,endTime);
                }
                if(strList.size()>0){
                    for(String str:strList){
                        KyOrganizationParameters koparam = new KyOrganizationParameters();
                        Date strDate =sdf.parse(str);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(strDate);
                        int yearOne = calendar.get(Calendar.YEAR);
                        int monthOne = calendar.get(Calendar.MONTH);
                        if(yearOnce==yearOne&&monthOnce==monthOne){
                            continue;
                        }
                        koparam.setOrganizationId(kop.getOrganizationId());
                        koparam.setPipeLength(kop.getPipeLength());
                        koparam.setFreeWaterConsumption(kop.getFreeWaterConsumption());
                        koparam.setNoWaterConsumption(kop.getNoWaterConsumption());
                        koparam.setFeeWaterConsumption(kop.getFeeWaterConsumption());
                        koparam.setBackgroundLeakage(kop.getBackgroundLeakage());
                        koparam.setMeasureErrer(kop.getMeasureErrer());
                        koparam.setOtherLossWater(kop.getOtherLossWater());
                        koparam.setLinkman(kop.getLinkman());
                        koparam.setPhone(kop.getPhone());
                        koparam.setYear(yearOne);
                        koparam.setMonth(monthOne);
                        koparam.setRemark(kop.getRemark());
                        kopList.add(koparam);
                    }
                }

            }
        }
        kyOrganizationParametersService.insertBatch(kopList);
        return R.ok();
    }
}
